<template>
    <div>
        <!-- <searchForm :searchArr="searchArr" @onSubmit="onSubmit"></searchForm> -->
        <div class="gva-table-box">
            <LTable
                v-if="isRenderIl8"
                :columns="columns"
                :tableData="tableData"
                @updateMultipleSelection="handleSelectionChange"
                :pages="pages"
                @changePages="changePages"
                @rowDblclick="(row) => openEditDialog(row, true)"
                :maxHeight="'calc(100vh - 226px)'"
                :searchArr="searchArr"
                :isSearch="true"
                @onSubmit="onSubmit"
                tableName="largeOrder"
                :export="true"
            >
                <template #action>
                    <div class="gva-btn-list" >
                        <el-button
                        v-if="userStore.userInfo.authority?.authorityId !== 1000"
                            type="primary"
                            icon="plus"
                            @click="openCreateDialog"
                            >新增</el-button
                        >
                        <!-- <el-button
                            type="primary"
                            icon="edit"
                            :disabled="multipleSelection.length!=1"
                            @click="openEditDialog(multipleSelection.length==1&&multipleSelection[0])"
                        >
                            编辑
                        </el-button> -->
                        <el-button
                        v-if="userStore.userInfo.authority?.authorityId !== 1000"
                            type="primary"
                            icon="delete"
                            v-auth="btnAuth.batchDel"
                            :disabled="!multipleSelection.length"
                            @click="deleteRow"
                            >删除</el-button
                        >
                        <el-button
                            type="primary"
                            class="table-button"
                            :disabled="multipleSelection.length != 1"
                            @click="historyVision"
                        >
                            历史版本
                        </el-button>
                        <!-- <historyRecord v-if="userStore.userInfo.authority?.authorityId !== 1000" name="orderProcessing"  :datas="multipleSelection.length == 1 && multipleSelection[0].largeScaleNum"></historyRecord> -->
                        <relatedBtn
                        v-if="userStore.userInfo.authority?.authorityId !== 1000"
                            :disabled="multipleSelection.length != 1"
                            :row="
                                multipleSelection.length == 1 &&
                                multipleSelection[0]
                            "
                            :modalType="'largeScaleOrder'"
                        />
                        <el-button type="primary" @click="batchCompleteUpload" v-if="userStore.userInfo.authority?.authorityId !== 1000"
                            >办单批量完成模板</el-button
                        >
                        <el-upload
                        v-if="userStore.userInfo.authority?.authorityId !== 1000"
                            :action="`${path}/largeScaleOrder/batchComplete`"
                            :on-error="uploadError"
                            accept=".xlsx, .xls"
                            :before-upload="beforeUpload"
                            :on-success="uploadSuccess"
                            :headers="{
                                'x-token': xToken,
                                'x-user-id': xUserId,
                                Authorization: `Bearer ${xToken}`,
                            }"
                            :show-file-list="false"
                            class="upload-btn"
                        >
                            <el-button :loading="uploadLoading" type="primary" v-if="userStore.userInfo.authority?.authorityId !== 1000"
                                >办单批量完成导入</el-button
                            >
                        </el-upload>
                    </div>
                </template>
                <template #isExportChild="{ row }">
                    <span :style="{color:row.isExport=='是'?'red':''}">{{row.isExport}}</span>
                </template>
                <template #isExportToSapChild="{ row }">
                    <span :style="{color:row.isExportToSap=='是'?'red':''}">{{row.isExportToSap}}</span>
                </template>
                <template #printStatusChild="{ row }">
                    <span v-if="row.printStatus == '已打印'" style="color:red">{{row.printStatus}}</span>
                    <span v-else>{{row.printStatus}}</span>
                </template>

                <template #q1="{ row }">
                    <span >{{row.mold_house?.length? formatDate(row.mold_house[0].deliveryDate):''}}</span>
                </template>
                <template #q2="{ row }">
                    <span >{{row.mold_house?.length&&row.mold_house?.length>1? formatDate(row.mold_house[1].deliveryDate):''}}</span>
                </template>
                <template #q3="{ row }">
                    <span >{{row.mold_house?.length? formatDate(row.mold_house[row.mold_house.length-1].deliveryDate):''}}</span>
                </template>
                <template #q4="{ row }">
                    <span >{{row.mold_house?.length? row.mold_house[row.mold_house.length-1].detailDescription:''}}</span>
                </template>
                <template #FirstCreatedAt="{ row }">
                    <span v-if="row.FirstCreatedAt">{{formatDate(row.FirstCreatedAt)=="1-01-01" ? '' : formatDate(row.FirstCreatedAt) }}</span>
                </template>
                <!-- <template #largeScaleNum="scope">
                    <el-popover
                        placement="right"
                        :width="80"
                        trigger="hover"
                    >
                        <template #reference>
                            {{ scope.row.largeScaleNum }}
                        </template>
                        <div class="m-action-btns">
                            <el-button
                                type="primary"
                                link
                                class="table-button"
                                icon="edit"
                                @click="openEditDialog(scope.row)"
                            >
                                编辑
                            </el-button>
                            <el-button
                                type="primary"
                                link
                                icon="delete"
                                class="table-button"
                                @click="deleteRow(scope.row)"
                                >删除</el-button
                            >
                            <relatedBtn
                                :row="scope.row"
                                :modalType="'largeScaleOrder'"
                            />
                        </div>
                    </el-popover>
                </template> -->
                <!-- <template #event>
                    <el-table-column
                        align="left"
                        label="操作"
                        fixed="right"
                        min-width="320"
                        width="320"
                    >
                        <template #default="scope">
                            <el-button
                                type="primary"
                                link
                                class="table-button"
                                icon="edit"
                                @click="openEditDialog(scope.row)"
                            >
                                编辑
                            </el-button>
                            <el-button
                                type="primary"
                                link
                                icon="delete"
                                class="table-button"
                                @click="deleteRow(scope.row)"
                                >删除</el-button
                            >
                            <relatedBtn
                                :row="scope.row"
                                :modalType="'largeScaleOrder'"
                            />
                            <el-button type="primary" link icon="discount"
                                >历史版本</el-button
                            >
                        </template>
                    </el-table-column>
                </template> -->
            </LTable>
        </div>
        <el-dialog v-model="historyVisionShow" title="历史版本" width="900">
            <el-table
                ref="multipleTableRef"
                :data="historyList"
                :row-class-name="tableRowClassName"
                @rowDblclick="rowDblclickFun"
                style="width: 100%"
            >
                <el-table-column prop="styleNum" label="款式编号" />
                <el-table-column prop="largeScaleNum" label="大办单编号" />
                <el-table-column prop="localStyleNum" label="本厂款号" />
                <el-table-column prop="cumstomerNum" label="客户款号" />
                <el-table-column prop="version" label="版本" />
                <el-table-column prop="createdAt" label="创建时间">
                    <template #default="scope">
                        <span>
                            {{ formatDate(scope.row.CreatedAt) }}
                        </span>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
    </div>
</template>

<script setup>
import {
    deleteLargeScaleOrder,
    deleteLargeScaleOrderByIds,
    findLargeScaleOrder,
    getLargeScaleOrderList,
    getLargeScaleOrderHistoryList
} from "@/api/plmLargeScaleOrder";
import historyRecord from "@/components/historyRecord/historyRecord.vue";
// 全量引入格式化工具 请按需保留
import {
    getDictFunc,
    formatDate,
    formatBoolean,
    filterDict,
    ReturnArrImg,
    onDownloadFile,
} from "@/utils/format";
import LTable from "@/components/LTable/LTable.vue";
// import searchForm from "@/components/searchForm/searchForm.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, reactive, onMounted, watchEffect, watch } from "vue";
import { useUserStore } from "@/pinia/modules/user";
import { useRouter, useRoute } from "vue-router";
import { useI18n } from "vue-i18n";
import { useDict } from "@/utils/dictionary";
import dayjs from "dayjs";
const dict = ref({});
const { t: il8n } = useI18n();

defineOptions({
    name: "FirstOrderProcessing",
});
// 使用 useRoute 函数获取当前路由信息
const router = new useRouter();
const route = new useRoute();

import { useBtnAuth } from "@/utils/btnAuth";
const btnAuth = useBtnAuth();

// 验证规则
const rule = reactive({});

// const

const searchRule = reactive({
    createdAt: [
        {
            validator: (rule, value, callback) => {
                if (
                    searchInfo.value.startCreatedAt &&
                    !searchInfo.value.endCreatedAt
                ) {
                    callback(new Error("请填写结束日期"));
                } else if (
                    !searchInfo.value.startCreatedAt &&
                    searchInfo.value.endCreatedAt
                ) {
                    callback(new Error("请填写开始日期"));
                } else if (
                    searchInfo.value.startCreatedAt &&
                    searchInfo.value.endCreatedAt &&
                    (searchInfo.value.startCreatedAt.getTime() ===
                        searchInfo.value.endCreatedAt.getTime() ||
                        searchInfo.value.startCreatedAt.getTime() >
                            searchInfo.value.endCreatedAt.getTime())
                ) {
                    callback(new Error("开始日期应当早于结束日期"));
                } else {
                    callback();
                }
            },
            trigger: "change",
        },
    ],
});

const elFormRef = ref();
const elSearchFormRef = ref();

// =========== 表格控制部分 ===========

const tableData = ref([]);
const searchInfo = ref({});

const pages = ref({
    page: 1,
    pageSize: 20,
    total: 0,
});

const isRenderIl8 = ref(false);

// ======查询数据======
const searchArr = ref([]);
// ======表格头部数据======
const columns = ref([]);

watchEffect(() => {
    const newSearchArr = [
        {
            prop: "styleNum",
            label: il8n("styleNum.label"),
            show: true, // 通过 show 来控制列的展示或隐藏
            value: "",
            type: "input",
        },
        {
            prop: "largeScaleNum",
            label: "大办单编号",
            show: true, // 通过 show 来控制列的展示或隐藏
            value: "",
            type: "input",
            placeholder: "请输入",
        },
        {
            prop: "localStyleNum",
            label: "本厂款号",
            show: true, // 通过 show 来控制列的展示或隐藏
            value: "",
            type: "input",
        },
        {
            prop: "cumstomerNum",
            label: il8n("cumstomerNum.label"),
            show: true,
            value: "",
            type: "input",
        },
        {
            prop: "customerStyleNum",
            label: il8n("customerStyleNum.label"),
            show: true,
            value: "",
            type: "input",
        },
        {
            prop: "printStatus",
            label: il8n("printStatus.label"),
            show: true,
            value: "",
            selectList: [
                { label: "未打印", value: "未打印" },
                { label: "已打印", value: "已打印" },
            ],
            type: "select",
        },
        {
            prop: "status",
            label: "当前状态",
            show: true,
            selectList: dict.value.fopStatus,
            type: "select",
            value: "",
        },
        {
            prop: "isExport",
            label: il8n("isExport.label"),
            show: true,
            value: "",
            selectList: [
                { label: "是", value: "1" },
                { label: "否", value: "0" },
            ],
            type: "select",
        },
        {
            prop: "isExportToSap",
            label: il8n("isExportToSap.label"),
            show: true,
            value: "",
            selectList: [
                { label: "是", value: "1" },
                { label: "否", value: "0" },
            ],
            type: "select",
        },
        {
            prop: "productionDepartment",
            label: "制作部門",
            show: true, // 通过 show 来控制列的展示或隐藏
            value: "",
            type: "select",
            selectList:dict.value.productionDepartment
        },
        {
            prop: "customerDemandDate",
            label: il8n("customerDemandDate.label"),
            show: true, // 通过 show 来控制列的展示或隐藏
            value: "",
            type: "datetimerange",
        },
        {
            prop: "createUser",
            label: "创建人",
            show: true,
            value: "",
            type: "input",
        },
        {
            prop: "CreatedAt",
            label: il8n("createdAt.label"),
            show: true, // 通过 show 来控制列的展示或隐藏
            value: "",
            type: "datetimerange",
        },
        {
            prop: "updateUser",
            label: "更新人",
            show: true, // 通过 show 来控制列的展示或隐藏
            value: "",
            type: "input",
        },
        {
            prop: "UpdatedAt",
            label: "更新日期",
            show: true, // 通过 show 来控制列的展示或隐藏
            value: "",
            type: "datetimerange",
        },
        {
            prop: "orderAmountSum",
            fixedWidth: 100,
            label: "办单付数",
            show: true,
            value: "",
            type: "input",
        },
        {
            prop: "version",
            label: "版本",
            show: true,
            value: "",
            type: "input",
        },
        {
            prop: "FirstCreatedAt",
            label: "第一版创建时间",
            show: true, // 通过 show 来控制列的展示或隐藏
            value: "",
            type: "datetimerange",
        },
        // {
        //     prop: "transferOrder",
        //     label: "生产地点",
        //     width: 100,
        //     show: true,
        //     value: "",
        //     type: "input",
        // },
    ];
    searchArr.value = [...newSearchArr];

    const newColumns = [
        {
            prop: "largeScaleNum",
            fixedWidth: 130,
            label: "大办单编号",
            show: true, // 通过 show 来控制列的展示或隐藏
            filter: true,
            // slot: "largeScaleNum",
            tableColumnProps: {
                fixed: "left",
            },
        },
        {
            prop: "localStyleNum",
            fixedWidth: 160,
            label: "本厂款号",
            show: true,
        },
        {
            prop: "customerStyleNum",
            fixedWidth: 120,
            label: il8n("customerStyleNum.label"),
            show: true,
        },
        {
            prop: "styleNum",
            fixedWidth: 130,
            label: il8n("styleNum.label"),
            show: true,
        },
        {
            prop: "orderAmountSum",
            fixedWidth: 100,
            label: "办单付数",
            show: true,
        },
        {
            prop: "cumstomerNum",
            fixedWidth: 120,
            label: il8n("cumstomerNum.label"),
            show: true,
        },
        {
            prop: "status",
            width: 130,
            label: il8n("ptlm_status.label"),
            show: true,
        },
        {
            prop: "printStatus",
            label: il8n("printStatus.label"),
            width: 100,
            show: true,
            childSlot:true,
            childSlotName:"printStatusChild"
        },
        {
            prop: "isExport",
            label: il8n("isExport.label"),
            fixedWidth: 100,
            show: true,
            childSlot:true,
            childSlotName:"isExportChild"
        },
        {
            prop: "isExportToSap",
            label: il8n("isExportToSap.label"),
            fixedWidth: 130,
            show: true,
            childSlot:true,
            childSlotName:"isExportToSapChild"
        },
        {
            prop: "productionDepartment",
            label: "制作部門",
            show: true, // 通过 show 来控制列的展示或隐藏
            fixedWidth: 120,
        },
        // {
        //     prop: "transferOrder",
        //     label: "生产地点",
        //     width: 100,
        //     show: true,
        // },
        {
            prop: "version",
            label: "版本",
            show: true,
        },
        {
            prop: "customerDemandDate",
            label: il8n("customerDemandDate.label"),
            width: 150,
            show: true, // 通过 show 来控制列的展示或隐藏
        },
        {
            prop: "createUser",
            label: "创建人",
            width: 100,
            show: true,
        },
        {
            prop: "CreatedAt",
            label: "创建时间",
            width: 100,
            show: true,
        },
        {
            prop: "updateUser",
            label: "更新人",
            width: 100,
            show: true,
        },
        {
            prop: "UpdatedAt",
            label: "更新时间",
            width: 100,
            show: true
        },
         // 新增付期的四列
         {
            prop: "q1",
            label:'第一次复期',
            show: true,
            fixedWidth: 150,
            slot:"q1"
        },
        {
            prop: "q2",
            label:'第二次复期',
            show: true,
            fixedWidth: 150,
            slot:"q2"
        },
        {
            prop: "q3",
            label:'最后一次复期',
            show: true,
            fixedWidth: 150,
            slot:"q3"
        },
        {
            prop: "q4",
            label:'最后一次复期原因',
            show: true,
            fixedWidth: 150,
            slot:"q4"
        },
        {
           prop: "FirstCreatedAt",
           label:'第一版本创建时间',
           show: true,
           fixedWidth: 150,
           // slot:"FirstCreatedAt"
        },
    ];
    columns.value = [...newColumns];
    setTimeout(() => {
        isRenderIl8.value = true;
    }, 0);
});

// 搜索
const onSubmit = (val) => {
    searchInfo.value = {
        ...val,
    };
    pages.value.page = 1;
    pages.value.pageSize = 20;
    getTableData();
};

// 修改页面容量
const handleCurrentChange = (val) => {
    getTableData();
};

// 查询
const getTableData = async () => {
    const params = {
        ...pages.value,
        ...searchInfo.value,
    };
    if (Array.isArray(params.customerDemandDate)&&params.customerDemandDate.length) {
        console.log();
      params.customerDemandStartDate = dayjs(params.customerDemandDate[0].substr(0,10)+'00:00:00').format('YYYY-MM-DDTHH:mm:ssZ') || "";
      params.customerDemandEndDate = dayjs(params.customerDemandDate[1].substr(0,10)+'23:59:59').format('YYYY-MM-DDTHH:mm:ssZ') || "";
      delete params.customerDemandDate ;
    }
    delete params.createdAt;
    delete params.updatedAt;
    const table = await getLargeScaleOrderList(params);
    if (table.code === 0) {
        tableData.value = table.data.list.map(m => {
            return {
                ...m,
                customerDemandDate: m.customerDemandDate
                    ? formatDate(m.customerDemandDate)
                    : "",
                      FirstCreatedAt: formatDate(m.FirstCreatedAt)=="1-01-01"
                      ? ""
                   : formatDate(m.FirstCreatedAt),
                CreatedAt: m.CreatedAt ? formatDate(m.CreatedAt) : "",
                UpdatedAt: m.UpdatedAt ? formatDate(m.UpdatedAt) : "",
                isExport:m.isExport==1?'是':m.isExport==0?'否':'',
                isExportToSap:m.isExportToSap==1?'是':m.isExportToSap==0?'否':''
            };
        });
        pages.value.total = table.data.total;
        pages.value.page = table.data.page;
        pages.value.pageSize = table.data.pageSize;
    }
};

// ============== 表格控制部分结束 ===============

// 多选数据
const multipleSelection = ref([]);
// 多选
const handleSelectionChange = (val) => {
    multipleSelection.value = val;
};

// 删除行
const deleteRow = () => {
    // ElMessageBox.confirm("确定要删除吗?", "提示", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     type: "warning",
    // }).then(() => {
    //     deleteLargeOrderProcessingFunc(row);
    // });
    ElMessageBox.confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(async () => {
        const IDs = [];
        if (multipleSelection.value.length === 0) {
            ElMessage({
                type: "warning",
                message: "请选择要删除的数据",
            });
            return;
        }
        multipleSelection.value &&
            multipleSelection.value.map((item) => {
                IDs.push(item.ID);
            });
        const res = await deleteLargeScaleOrderByIds({ IDs });
        if (res.code === 0) {
            ElMessage({
                type: "success",
                message: "删除成功",
            });
            if (tableData.value.length === IDs.length && pages.value.page > 1) {
                pages.value.page--;
            }
            getTableData();
        }
    });
};

// 行为控制标记（弹窗内部需要增还是改）
const type = ref("");

// 删除行
const deleteLargeOrderProcessingFunc = async (row) => {
    const res = await deleteLargeScaleOrder({ ID: row.ID });
    if (res.code === 0) {
        ElMessage({
            type: "success",
            message: "删除成功",
        });
        // if (tableData.value.length === 1 && page.value > 1) {
        //   page.value--;
        // }
        getTableData();
    }
};

// 打开弹窗
const openCreateDialog = () => {
    // 打开弹窗
    router.push({
        path: "/layout/plmLargeOrderProcessingAdd",
    });
};

const openEditDialog = (row, isView) => {
    // 打开弹窗
    router.push({
        path: "/layout/plmLargeOrderProcessingEdit",
        query: { id: row.largeScaleNum, subTitle: row.largeScaleNum, isView },
    });
};

// 办单批量完成
const path = ref(import.meta.env.VITE_BASE_API);
const userStore = useUserStore();
const xToken = ref("");
const xUserId = ref("");
xToken.value = userStore.token;
xUserId.value = userStore.userInfo.ID;
const uploadLoading = ref(false);
// 限制只能上传excel
function beforeUpload(file) {
    //获取上传文件
    let formData = new FormData(); //FormData对象，添加参数只能通过append('key', value)的形式添加
    formData.append("file", file); //添加文件对象
    const Xls = file.name.split(".")[file.name.split(".").length - 1];
    if (Xls === "xls" || Xls === "xlsx" || Xls === "csv") {
        uploadLoading.value = true;
        return file;
    } else {
        ElMessage({
            type: "error",
            message: "请上传excel格式的文件!",
        });
        return false;
    }
}

const uploadSuccess = (res) => {
    uploadLoading.value = false;
    if (res.code == 0) {
        const { data } = res;
        onSubmit();
        const fileUrl = path.value + data.fileUrl;
        const link = document.createElement("a");
        link.href = fileUrl;
        // link.setAttribute("download", row.drawingName);
        link.click();
    } else {
        ElMessage({
            type: "error",
            message: res.msg,
        });
    }
};
const uploadError = () => {
    uploadLoading.value = false;
    ElMessage({
        type: "error",
        message: "上传失败",
    });
};
const batchCompleteUpload = () => {
    const path1 = ref(import.meta.env.VITE_BASE_PATH);
    const File = "/output/batchcomplete.xlsx";
    var xml = new XMLHttpRequest();
    xml.open("GET", path1.value + File, true);
    xml.responseType = "blob";
    xml.onload = function () {
        var url = window.URL.createObjectURL(xml.response);
        var a = document.createElement("a");
        a.href = url;
        a.download = "办单批量完成.xlsx";
        a.click();
    };
    xml.send();
};

// 历史版本shou
const historyVisionShow = ref(false);
let historyList = ref([]); // 历史版本数据
// 历史版本
const historyVision = () => {
    historyList.value = [];
    let sel = multipleSelection.value[0];
    historyVisionShow.value = true;
    getLargeScaleOrderHistoryList({ largeScaleNum: sel.largeScaleNum }).then((res) => {
        if (res.code == 0) {
            historyList.value = res.data.list;
        }
    });
};
const rowDblclickFun = (row, column) => {
    historyVisionShow.value = false;
    if(row.ID == historyList.value[0].ID){
        router.push({
            path: "/layout/plmLargeOrderProcessingEdit",
            query: { id: row.largeScaleNum, subTitle: row.largeScaleNum, isView:true },
        });
    }else{
        router.push({
            path: "/layout/plmLargeOrderProcessingEdit",
            query: { 
                id: row.largeScaleNum, 
                subTitle: row.largeScaleNum ? row.largeScaleNum : undefined, 
                isView: row.index === 0 ? 0 : 1,  
                version: row.version,
                enableEdit: row.index === 0
            },
        });
    }
};

const tableRowClassName = ({row, rowIndex}) => {
    row.index = rowIndex;
}

onMounted(async () => {
    dict.value = await useDict("fopStatus",'productionDepartment');
    // searchArr.value[5].selectList = [
    //     { label: "未打印", value: "未打印" },
    //     { label: "已打印", value: "已打印" },
    // ];
    // let index = searchArr.value.findIndex(item=>{
    //     return item.prop == 'status'
    // })
    // if(index!=-1){
    //     searchArr.value[index].selectList = dict.value.fopStatus;
    // }
    // searchArr.value[6].selectList = dict.value.fopStatus;
    // getTableData();
});

function updateMultipleSelection() {}

function changePages(currentPages) {
    pages.value = {
        ...pages.value,
        ...currentPages,
    };
    getTableData();
}

watch(() => route.path, (newPath, oldPath) => {
//   console.log('路由已变更：', `从 ${oldPath} 到 ${newPath}`);
    if(newPath == '/layout/plmLargeOrderProcessing'){
        getTableData();
    }
},{immediate:true});

</script>

<style lang="scss" scoped>
@import url("@/style/common/common.scss");
</style>
